<template>
    <div>
        <h1>用户登录</h1>
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="form.userName" name="userName" label="用户名" placeholder="用户名"
                    :rules="rules.userName" />
                <van-field v-model="form.passWord" type="password" name="passWord" label="密码" placeholder="密码"
                    :rules="rules.passWord" />
            </van-cell-group>
            <div class="login-btn">
                <van-button round block type="primary" native-type="submit">登录</van-button>
            </div>
        </van-form>
    </div>
</template>

<script setup name="login">
import { reactive, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
// 获取当前vue实例
const { proxy } = getCurrentInstance()

// 表单数据
const form = reactive({
    userName: '',
    passWord: ''
})


// 验证用户名：手机号
const validatorUserName = (value) => {
    if (value === '') {
        return '请输入手机号'
    } else {
        const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
        return phoneReg.test(value) ? true : '手机号格式不正确，请输入正确的手机号'
    }
}

// 验证密码：4-16位字母数字下划线
const validatorPassWord = (value) => {
    if (value === '') {
        return '请输入密码'
    } else {
        const phoneReg = /^[a-zA-Z0-9_-]{4,16}$/
        return phoneReg.test(value) ? true : '密码格式不正确，请输入正确的密码'
    }
}

// 表单验证  trigger: 'blur' 失去焦点时触发
const rules = reactive({
    // 用户名
    userName: [{ validator: validatorUserName, trigger: 'blur' }],
    // 密码
    passWord: [{ validator: validatorPassWord, trigger: 'blur' }],
})

// 表单提交
const onSubmit = async () => {
    try {
        // 调用登录接口返回数据
        const { data } = await proxy.$api.login(form)
        // 如果登录成功，将token和用户信息存储到本地
        if (data.code === 10000) {
            localStorage.setItem('h5_token', data.data.token)
            localStorage.setItem('h5_userInfo', JSON.stringify(data.data.userInfo))
            // 跳转首页
            router.push('/home')
        } else {
            console.error('登录失败:', data.msg)
        }
    } catch (error) {
        console.error('登录失败:', error)
    }
}
</script>

<style lang="less" scoped>
h1 {
    text-align: center;
    margin-top: 100px;
}

.login-btn {
    margin: 16px;
}
</style>